import React, { PureComponent, Fragment } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'dva';
import { Link } from 'dva/router';
import {
  Table,
  Icon,
  Divider,
  Form,
  Select,
  DatePicker,
  Input,
  Card,
  Tag,
  message,
  Checkbox,
  Rate,
  Badge,
  Button,
  Dropdown,
  Row,
  Col,
  Modal,
  Collapse,
  List,
  Radio,
} from 'antd';

import PageHeaderLayout from '../../../layouts/PageHeaderLayout';
import ImageUploader from '../../../components/Falcon/Attachment/ImageUploader';
import ApplyOrderDisplayer from '../../../components/Falcon/ApplyOrderDisplayer';

import styles from './style.less';
const confirm = Modal.confirm;
const Panel = Collapse.Panel;
const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const { TextArea } = Input;
const Option = Select.Option;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');
const statusMap = ['default', 'processing', 'error', 'success', 'error'];
const reportState = ['未上报', '银行审核中', '驳回', '通过', '否决'];
const creditStateArray = ['未查询', '已查询', '查询中'];

@connect(({ risk, apply }) => ({
  risk,
  apply,
}))
export default class ReportBrankList extends PureComponent {
  state = {
    projectId: '',
    modalVisible: false,
    riskCustManager: null,
    bankCustomerManager: null,
    branckName: '',
    formValues: {},
    cities: null,
    secondCity: null,
    cityData: null,
    provinceData: null,
    submitBranchResult: false,
    bizStateStr: null,
    paramsValue: null,
    branchSupplement: false,
    branchSupplementId: null
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'risk/getReportList',
      payload: {
        offset: 0,
        limit: 10,
      },
    });

    dispatch({
      type: 'risk/selectCustManager',
      callback: () => {
        const { risk: { riskCustManager } } = this.props;
        const { bankNameList, infoList } = riskCustManager;
        riskCustManager &&
          this.setState({
            riskCustManager,
            provinceData: bankNameList,
            cityData: infoList,
          });
        // console.log("bankCustomerManager", infoList)
      },
    });
  }

  tableColumns = [
    { title: '业务编号', dataIndex: 'bizNum', key: 'bizNum' },
    { title: '客户姓名', dataIndex: 'custName', key: 'custName' },
    { title: '产品', dataIndex: 'productName', key: 'productName' },
    {
      title: '上报状态',
      dataIndex: 'bizState',
      key: 'bizState',
      filters: [
        {
          text: reportState[0],
          value: 1,
        },
        {
          text: reportState[1],
          value: 2,
        },
        {
          text: reportState[2],
          value: 3,
        },
        {
          text: reportState[3],
          value: 4,
        },
        {
          text: reportState[4],
          value: 5,
        },
      ],
      render(val) {
        return <Badge status={statusMap[val - 1]} text={reportState[val - 1]} />;
      },
    },
    {
      title: '征信筛查',
      dataIndex: 'creditState',
      key: 'creditState',
      align: 'center',
      render(val) {
        switch (val) {
          case 0:
            return <Tag color="red">{creditStateArray[val]}</Tag>;
          case 1:
            return <Tag color="green">{creditStateArray[val]}</Tag>;
          case 2:
            return <Tag color="orange">{creditStateArray[val]}</Tag>;
        }
      },
    },
    { title: '创建时间', dataIndex: 'createTime', key: 'createTime' },
    {
      title: '操作',
      width: '20%',
      render: (text, record) => (
        <Fragment>
          {/* 1：未上报；2：银行审核中；3：驳回：4：通过；5：否决 */}
          {record.bizState == 1 ? <a onClick={() => this.handleConfirm(record)}>上报</a> : null}
          {record.bizState == 3 ? (
            <div>
              <Link to={`fillApply?id=${record.id}&taskId=${record.taskId}&applyDisabled=${1}`}>
                审批详情
              </Link>
              <Divider type="vertical" />
              <Link to={`fillApply?id=${record.id}&taskId=${record.taskId}&applyDisabled=${2}`}>
                补录
              </Link>
            </div>
          ) : null}
          {record.bizState == 5 ? (
            <a onClick={() => this.handleSubmitBranchConfirm(record)}>审批详情</a>
          ) : null}
          {record.bizState == 4 ?
            <div>
              <a onClick={() => this.handleSubmitBranchConfirm(record)}>审批详情</a>
              <Divider type="vertical" />
              <a onClick={() => this.handleSubmitBranchSupplement(record)}>补导入</a>
            </div>
            : null
          }
        </Fragment>
      ),
    },
  ];

  handleConfirm = record => {
    this.setState({ modalVisible: true, projectId: record.id });
  };

  handleSubmitBranchSupplement = (record) => {
    this.setState({branchSupplement: true, branchSupplementId: record.id})
  }

  handleBranchSupplementOK = () =>{
    const { dispatch } = this.props;//补导入
    dispatch({
      type: 'apply/submitData',
      payload: {
        projectId: this.state.branchSupplementId,
      },
      callback: () => {
        const { apply: { applyResult } } = this.props;
        if (applyResult.code == 200) {
          this.setState({ modalVisible: false, branchSupplement: false });
          message.success('导入成功,15分钟内请勿重复操作');
          dispatch({
            type: 'risk/getReportList',
            payload: {
              ...this.state.paramsValue,
              bizStateStr: this.state.bizStateStr,
            },
          });
        } else {
          message.error(riskResult.message);
        }
      }
    })
  }

  handleBranchSupplementCancel = () =>{
    this.setState({branchSupplement: false})
  }

  handleBranchManageOK = () => {
    const { dispatch } = this.props;
    if (this.state.secondCity) {
      dispatch({
        type: 'risk/businnesSubmitToBank',
        payload: {
          projectId: this.state.projectId,
          userName: this.state.secondCity,
        },
        callback: () => {
          const { risk: { riskResult } } = this.props;

          if (riskResult.code == 200) {
            this.setState({ modalVisible: false });
            message.success('上报成功');
            dispatch({
              type: 'risk/getReportList',
              payload: {
                offset: 0,
                limit: 10,
              },
            });
          } else {
            message.error(riskResult.message);
          }
        },
      });
    } else {
      message.warning('请选择客户经理');
    }
  };

  handleSubmitBranchConfirm = record => {
    const { dispatch } = this.props;
    dispatch({
      type: 'apply/getBankApprovalList',
      payload: {
        projectId: record.id,
      },
      callback: () => {
        const { apply: { submitBranchList } } = this.props;
      },
    });
    this.setState({
      submitBranchResult: true,
    });
  };

  handleSubmitBranchresultOK = () => {
    this.setState({
      submitBranchResult: false,
    });
  };

  handleSubmitBranchresultCancel = () => {
    this.setState({
      submitBranchResult: false,
    });
  };

  handleBranckManageCancel = () => {
    this.setState({ modalVisible: false, secondCity: null });
  };

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      offset: (pagination.current - 1) * pagination.pageSize,
      limit: pagination.pageSize,
      ...formValues,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }
    let bizStateStr = null;
    if (params.bizState) {
      bizStateStr = params.bizState;
    }
    this.setState({ paramsValue: params, bizStateStr: bizStateStr })
    dispatch({
      type: 'risk/getReportList',
      payload: {
        ...params,
        bizStateStr,
      },
    });
  };

  handleBranckChange = value => {
    this.setState({ secondCity: value });
  };

  handleProvinceChange = value => {
    this.setState({
      cities: this.state.cityData[value],
      secondCity: this.state.cityData[value][0] && this.state.cityData[value][0].userName,
    });
  };
  
  render() {
    const { risk: { riskReportList, riskHomeVisitLoading, riskPage } } = this.props;
    const { apply: { applyBranchList, applyPickCarLoading ,applyLoading} } = this.props;
    const { provinceData, cities, riskCustManager } = this.state;

    const provinceOptions =
      provinceData && provinceData.map(province => <Option key={province}>{province}</Option>);
    const cityOptions =
      cities &&
      cities.map(
        options => <Option key={options.userName}>{options.name}</Option>
        // console.log(" this.state.cities&&t",  options)
      );

    return (
      <PageHeaderLayout title="上报银行">
        <Card>
          {/* {JSON.stringify(riskReportList )} */}
          <Table
            pagination={riskPage}
            loading={riskHomeVisitLoading}
            rowKey="id"
            dataSource={riskReportList}
            columns={this.tableColumns}
            onChange={this.handleStandardTableChange}
          />
        </Card>
        <Modal
          title="选择客户经理"
          confirmLoading={riskHomeVisitLoading}
          visible={this.state.modalVisible}
          onCancel={this.handleBranckManageCancel}
          onOk={this.handleBranchManageOK}
        >
          <Row>
            <Col>
              {/* 选择客户经理： */}
              <div style={{ textAlign: 'center' }}>
                <Select
                  style={{ width: 150, marginRight: '20px' }}
                  onChange={this.handleProvinceChange}
                >
                  {provinceOptions}
                </Select>
                <Select
                  value={this.state.secondCity}
                  style={{ width: 150, marginLeft: '20px' }}
                  onChange={this.handleBranckChange}
                >
                  {cityOptions}
                </Select>
              </div>
            </Col>
          </Row>
        </Modal>

        <Modal
          title="银行审批结果"
          confirmLoading={applyPickCarLoading}
          visible={this.state.submitBranchResult}
          onCancel={this.handleSubmitBranchresultCancel}
          onOk={this.handleSubmitBranchresultOK}
        >
          <Row>
            <Collapse>
              {applyBranchList &&
                applyBranchList.map(item => {
                  return (
                    <Panel header={item.displayName + '  ' + item.updateTime} key={item.id}>
                      <p>任务名称：{item.displayName}</p>
                      <p>操作时间：{item.createTime}</p>
                      <p>处理人：{item.opname}</p>
                      <p>审核结果：{item.result}</p>
                      <p>审核意见：{item.content}</p>
                    </Panel>
                  );
                })}
            </Collapse>
          </Row>
        </Modal>

        <Modal
          title="补导入"
          confirmLoading={applyLoading}
          visible={this.state.branchSupplement}
          onCancel={this.handleBranchSupplementCancel}
          onOk={this.handleBranchSupplementOK}
        >
          <p style={{fontSize:'16px',textAlign:'center'}}>你确定要补导入吗？</p>
        </Modal>
      </PageHeaderLayout>
    );
  }
}
